/**
 * @module NGS.plugins
 * @description NGS 系统插件
 * @author don
 */
"use strict";

define(['js/lib/async.min', 'js/plugins/chat/chat.common.js', 'js/plugins/chatUtils/i18n/chatUtils.' + $E.lang, 'js/plugins/chatUtils/vue.component.chat.js', 'js/lib/vue.min'], function (async, $COMM, i18n, $COMP, Vue) {
    /**
     *  #########  聊天工具类  #########
     * @param project
     * @param container
     * @returns {chatUtils.ChatUtils}
     * @constructor
     */
    var ajaxURL = "agentService.do"
        , typeForuser = 'CHATSFORUSER'
        , typeForAgent = 'SESSIONLISTFORAGENT'
        , typeForSearch = 'SEARCHLISTFORAGENT'
        , divType = typeForAgent;
    var vmUserId;
    var ChatUtils = function (project, container, parameter) {
        var c = this, userId = '', sessionId = 0, chatServerAddr = '', chatServerHost = '', chatServerName = '',
            chatEvent = false, clientid = '', qualityTest = '', chatStyle;

        //按钮显示和隐藏控制
        var clientHis = false, agentList = false, searchBtn = false;
        //CHTSTY 表示 chat插件使用的样式
        chatStyle = project.getParam('CHTSTY') || 'chat';
        this.project = project;
        this.container = container;
        this.parameter = parameter;
        var ajaxURL = "agentService.do"
            , EMOTION = $COMM.EMOTION
            , ICONS = $COMM.ICONS
            , REQUEST_STATUS = $COMM.REQUEST_STATUS
            , CHAT_REQUEST_TYPE = $COMM.CHAT_REQUEST_TYPE
            , USER_STATUS = $COMM.USER_STATUS
            , CLIENT_TYPE = $COMM.CLIENT_TYPE
            , NOTICE_TYPE = $COMM.NOTICE_TYPE
            , Tools = $COMM.Tools
            , SoundManager = $COMM.SoundManager;
        var CHATTALK = $COMP.CHATTALK;

        chatServerAddr = project.getParam('CHATAD');

        if (location.hostname === "127.0.0.1" && location.port == 8088 || location.hostname === "localhost" && location.port === 8088) {
            chatServerAddr = 'http://' + location.hostname + ':8080/webchat';
        }

        $F.log('chatUtils-ServerAddr', chatServerAddr);
        if (chatServerAddr) {
            $COMP.init(chatServerAddr, project);
            chatServerHost = chatServerAddr.substring(0, chatServerAddr.lastIndexOf("/"));
            chatServerName = chatServerAddr.substring(chatServerAddr.lastIndexOf("/"), chatServerAddr.length);
        }


        var callService = function (url, data) {
            /** 通过服务端配置Access-Control-Allow-Origin实现的跨域，不需要使用跨域代理 */
            /** if (chatServerAddr !== (location.origin)) {*/
            /** url = $E.url + '/paramProxy?url=' + encodeURI(chatServerAddr  + chatServerName + "/" + url);*/
            /** } else {*/
            url = chatServerAddr + "/" + url;
            /** }*/
            var busyId = $F.busyShow('正在加载聊天插件数据');
            return $.ajax({
                xhrFields: {
                    withCredentials: true
                },
                timeout: 15000,
                cache: false,
                method: "POST",
                url: url,
                data: data
            }).fail(function (xhr) {
                $F.log('ChatUtils - ajax fail', xhr);
            }).always(function () {
                $F.busyHide(busyId);
            });
        };

        Vue.component('chat-talk', $COMP.CHATTALK);
        var init = function () {
            $F.log('chatUtils-init', 'UI开始初始化');
            //初始化组件
            new Vue({
                el: $('.chatUtils', container).get(0),
                data: function () {
                    return {
                        i18n: i18n,
                        viewClient: this.viewClient,
                        viewAgent: true,
                        clientBtn: true,
                        viewSearch: true,
                        toolBar: true,
                        active: 1,
                        sessionId: 0,
                        clientId: '',
                        chatEvent: false,
                        agentId: $E.staff.id,
                        saveChat: '',
                        markMessage: false,
                        heightLightKey: "",
                        keyword: '',
                        sessions: [],
                        sessionsForSearch: [],
                        url: chatServerAddr + '/' + ajaxURL,
                        name: 'chatTalkBySearchResult',// 'chatTalkByAgentSessionList',
                        token: c.project.token,
                        ds: $E.dataService.key,
                        activeName: '',
                        filetername: '',
                        filetersession: '',
                        fileterstart: '',
                        fileterend: '',
                        fileterrage: '',
                        qualityTest: ""
                    };
                },
                mounted: function () {
                    var self = this;
                    self.$nextTick(function () {
                        self.loading();
                    });
                },
                computed: {
                    showSessions() {
                        var showSessions = this.sessions;
                        if (this.filetersession > 0)
                            showSessions = showSessions.filter(item => ('' + item.sessionId).indexOf(this.filetersession + '') > -1);
                        if (this.filetername)
                            showSessions = showSessions.filter(item => ('' + item.clientName).indexOf(this.filetername + '') > -1);
                        if (this.fileterstart !== '') {
                            var filterStart = this.fileterstart;
                            filterStart = filterStart.split('-');
                            filterStart = filterStart[1] + '/' + filterStart[2] + '/' + filterStart[0];
                            showSessions = showSessions.filter(item => new Date(item.dateAndTime).getTime() > new Date(filterStart).getTime());
                        }
                        if (this.fileterend !== '') {
                            var filterEnd = this.fileterend;
                            filterEnd = filterEnd.split('-');
                            filterEnd = filterEnd[1] + '/' + filterEnd[2] + '/' + filterEnd[0];
                            showSessions = showSessions.filter(item => new Date(item.dateAndTime).getTime() < new Date(filterEnd).getTime());
                        }
                        return showSessions;
                    }
                },
                methods: {
                    change: function (msg) {
                        var self = this;
                        $F.log("chatUtils-change", '参数', msg);
                        self.active = msg;

                    },
                    changeUI: function (value) {
                        $F.log('chatUtils - changeUI', '切换界面', value);
                        var self = this;
                        self.active = value;
                        self.$emit('upup', value);
                    },
                    loading: function () {
                        var self = this;
                        if (parameter) {
                            if (parameter.MENUEVENT) {
                                $F.log("chatUtils-showTalksForDoubleClick", '菜单数据', parameter.MENUEVENT);
                                var parameterObj = JSON.parse(parameter.MENUEVENT);

                                if (parameterObj && parameterObj.showPerson) {
                                    self.viewAgent = true;
                                } else {
                                    self.viewAgent = false;
                                }

                                if (parameterObj && parameterObj.showAll) {
                                    self.clientBtn = true;
                                } else {
                                    self.clientBtn = false;
                                }

                                if (parameterObj && parameterObj.showSearchBtn) {
                                    self.viewSearch = true;
                                } else {
                                    self.viewSearch = false;
                                }
                                if (!self.viewSearch && !self.clientBtn && !self.viewAgent) {
                                    self.toolBar = false;
                                }

                                if (parameterObj && parameterObj.saveChat) {
                                    self.saveChat = true;
                                } else {
                                    self.saveChat = false;
                                }

                                if (parameter && parameter.markMessage) {
                                    self.markMessage = true;
                                } else {
                                    self.markMessage = false;
                                }

                                self.chatEvent = true;

                            } else {
                                if (parameter && parameter.ChatEvent) {
                                    $F.log("chatUtils-init", '[ 可以监听用户改变消息 ]');
                                    self.chatEvent = true;
                                } else {
                                    $F.log("chatUtils-init", '[ 不可以监听用户改变消息 ]');
                                    self.chatEvent = false;
                                }

                                // UI.showSessionListForAgent();
                                //clientHis = false, agentList = false, searchBtn = false;
                                if (parameter && parameter.showPerson) {
                                    self.viewAgent = true;
                                } else {
                                    self.viewAgent = false;
                                }

                                if (parameter && parameter.showAll) {
                                    self.clientBtn = true;
                                } else {
                                    self.clientBtn = false;
                                }

                                if (parameter && parameter.showSearchBtn) {
                                    self.viewSearch = true;
                                } else {
                                    self.viewSearch = false;
                                }
                                if (!self.viewSearch && !self.clientBtn && !self.viewAgent) {
                                    self.toolBar = false;
                                }

                                if (parameter && parameter.saveChat) {
                                    self.saveChat = true;
                                } else {
                                    self.saveChat = false;
                                }

                                if (parameter && parameter.markMessage) {
                                    self.markMessage = true;
                                } else {
                                    self.markMessage = false;
                                }

                                if (parameter.markId) {
                                    var markMessage = parameter.markMessage;
                                    var markId = parameter.markId;
                                    self.viewAgent = false;
                                    self.viewSearch = false;
                                    self.active = 0;
                                    callService(ajaxURL, {
                                        requestType: "initMarkMessage",
                                        sessionid: parameter.SessionId,
                                        markId: markId,
                                        agentId: $E.staff.id,
                                        token: this.token
                                    }).done(function (data) {
                                        $F.log("chatUtils-vue.component", "initMessages data for chat—talk", data);
                                        if (data.status === 'success') {
                                            self.sessionId = {
                                                canEdit: markMessage,
                                                sessionId: markId
                                            };
                                        } else {
                                            if (parameter.SessionId) {
                                                $F.log("chatUtils-init- forsession", "parameter", parameter);
                                                self.sessionId = parameter.SessionId;
                                            }
                                        }
                                    });
                                } else {
                                    if (parameter.UserId) {
                                        var userId = parameter.UserId;
                                        $F.log("chatUtils-init-forclientid", "parameter", parameter);
                                        if (userId) {
                                            self.clientId = userId;
                                            self.active = 0;
                                        }

                                    } else if (parameter.SessionId) {
                                        $F.log("chatUtils-init- forsession", "parameter", parameter);
                                        self.sessionId = parameter.SessionId;
                                        self.active = 0;
                                    } else {
                                        self.active = 1;
                                    }
                                }

                            }
                            // self.markMessage = true;
                            if (self.viewAgent) {
                                this.loadSessions();
                            }
                        }
                        //注册客户改变事件，chat中切换tab时候，会触发此事件
                        project.events.register($CONST.ChatEvent.CHAT_SESSION_CHANGED, c.id, function (data) {
                            $F.log('chatUtils', '是否要监听切换', self.chatEvent);
                            if (self.chatEvent) {
                                $F.log('chatUtils', '注册客户改变事件', data);
                                var session = data.session;//整个session的json对象
                                if (session && session.clientId) {
                                    self.clientId = session.clientId;
                                    self.active = 0;
                                }
                            }
                        });
                        //注册关键字改变事件，更改关键字之后可以改变界面上高亮内容
                        project.events.register($CONST.ChatUtil.CHANGE_HEIGHT_LIGHT_WORD, c.id, function (data) {
                            $F.log('chatUtils', '注册聊天历史高亮关键字', data);
                            var key = data.key;//整个session的json对象
                            if (key) {
                                self.heightLightKey = key;
                            }
                        });
                    },
                    loadSessions: function () {
                        var self = this;
                        callService(ajaxURL, {
                            requestType: 'getMyChatsSummary',
                            agentid: self.agentId,
                            token: this.token
                        }).done(function (data) {
                            $F.log("chatUtils_loadSessions", "getMyChatsSummary", data);
                            if (data.status === 'success') {
                                self.sessions = data.msgs;
                            } else {
                                $F.log('chatUtils - loadSessions', '请求失败');
                            }
                        }).fail(function (xhr) {
                            $F.log('chatUtils - loadSessions', "调用接口失败 getMyChatsSummary ");
                        });
                    },

                    //下面是关于搜索的
                    searchKeyWord: function () {
                        $F.log("chatUtils-search", "搜索", this.keyword);
                        var self = this;
                        callService(ajaxURL, {
                            requestType: 'searchSessionByKeyword',
                            userId: $E.staff.id,
                            url: chatServerAddr,
                            keyword: this.keyword,
                            token: this.token
                        }).done(function (data) {
                            $F.log("chatUtils-searchKeyWord", "getMyChatsSummary", data);
                            if (data.status === 'success') {
                                self.sessionsForSearch = data.msgs;
                            } else {
                                $F.log('请求失败');
                            }
                        }).fail(function (xhr) {
                            $F.log("chatUtils-searchKeyWord", "调用接口失败 getMyChatsSummary ");
                        });
                    },
                    heightLight: function (message) {
                        if (this.keyword) {
                            return message.replace(this.keyword, "<span style=\"background-color: #ff0; display: inline;\">" + this.keyword + "</span>");
                        } else {
                            return message;
                        }
                    },

                    showTalksForDoubleClick: function (sessionid) {
                        $F.log("chatUtils-showTalksForDoubleClick", "需要显示的sessionid", sessionid);
                        this.sessionId = sessionid;
                    }
                }
            });
        };

        H5Utils.loadPlugin({
            name: 'chatUtils',
            container: container,
            html: 'chatUtils/chat.html?' + new Date().getTime(),
            css: ['chat/' + chatStyle + '.css', 'chatUtils/' + chatStyle + '-transcript.css'],
            done: function (dom) {
                c.pluginDom = dom;
                init();
            }
        });
        return c;
    };
    ChatUtils.prototype = {
        /**
         * 重新激活插件，刷新插件数据
         * @method active
         * @param parameter {any} 插件入参
         */
        active: function (parameter) {
            if (this.parameter === parameter)
                return;
            this.parameter = parameter;
        },

        close: function () {
            $F.log('ChatUtils - close', '关闭聊天插件');
            this.project.events.remove(this.id);
            this.project.events.remove('CHANGE_HEIGHT_LIGHT_WORD');
            this.project.events.remove($CONST.ChatEvent.CHAT_SESSION_CHANGED);
            $(this.container).remove().html('');
            this.project = null;
            this.container = null;
            this.pluginDom.remove().html('');

        }
    };

    return {
        avaliable: function (project, addin, addinParam, parameter) {
            return {
                code: 1,
                message: 'OK'
            }
        },

        close: function () {
            $F.log('ChatUtils - close', arguments);
        },

        newInstance: function (project, container, addinParam, arguments4, parameter) {
            $F.log('ChatUtils - init', 'Version 1.0.3.3');
            return new ChatUtils(project, container, parameter);
        },

        destroy: function () {
            $F.log('ChatUtils - destroy', arguments);
        }
    };
});